package com.jeffpalm.pandoralastfm;

import java.io.IOException;
import java.util.Collection;

import net.roarsoftware.lastfm.Authenticator;
import net.roarsoftware.lastfm.Playlist;
import net.roarsoftware.lastfm.Result;
import net.roarsoftware.lastfm.Session;
import net.roarsoftware.lastfm.Track;
import net.roarsoftware.lastfm.User;

final class LastFm {

  public static LastFm getInstance(String username) {
    return new LastFm(username);
  }

  private final String user;
  private final String apiKey;
  private final String secret;
  private Session session;

  private LastFm(String user, String apiKey, String secret) {
    this.user = user;
    this.apiKey = apiKey;
    this.secret = secret;
  }

  private LastFm(String user) {
    this(user, API_KEY, SECRET);
  }

  LastFm() {
    this("spudtrooper");
  }

  private final static String API_KEY = "52081ce40c29189a5d69341b7b3676ba";
  private final static String SECRET = "d1da1a1befc76d10e271cf119c8c0fa5";

  public Session login() {
    if (session != null) return session;
    String token = Authenticator.getToken(apiKey);

    String url = "http://www.last.fm/api/auth/?api_key=" + apiKey + "&token=" + token;
    try {
      Browser.displayURL(url);
    } catch (IOException e) {
      e.printStackTrace();
    }

    while (true) {
      try {
        Session ses = Authenticator.getSession(token, apiKey, secret);
        if (ses != null) {
          this.session = ses;
          break;
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      try {
        Thread.sleep(3 * 1000);
      } catch (InterruptedException _) {}
    }
    return session;
  }

  public User getUser() {
    return User.getInfo(session);
  }

  public String getUsername() {
    return user;
  }

  public Collection<Playlist> getPlaylists() {
    return User.getPlaylists(user, apiKey);
  }

  public Result addTrack(Playlist playlist, String artist, String track) {
    return addTrack(playlist.getId(), artist, track);
  }

  public Result addTrack(int playlistId, String artist, String track) {
    login();
    return Playlist.addTrack(playlistId, artist, track, session);
  }
  
  public Result addTrackToDefaultPlaylist(String artist, String track) {
    Playlist playlist = null;
    for (Playlist pl : getPlaylists()) {
      playlist = pl;
      break;
    }
    Result res = null;
    if (playlist != null) {
      res = addTrack(playlist, artist, track);
    }
    return res;
  }
  

  public static void main(String[] args) {
    LastFm l = new LastFm();
    l.login();
    Playlist playlist = null;
    for (Playlist pl : l.getPlaylists()) {
      playlist = pl;
      break;
    }
    System.out.println(playlist.getTitle());
    for (Track t : playlist.getTracks()) {
      System.out.println(" - " + t.getArtist() + ":" + t.getLocation());
    }
  }

}
